﻿#region Copyright

// All Material Copyright © 2010 Dynamic Concepts Development Corp., All Rights Reserved.
//      Portions Copyright © 1984-2009 Dynamic Concepts Development Corp., All Rights Reserved.
// For further information please contact: SoftwareSupport@dynconcepts.com
// Dynamic Concepts Development Corp.  311 W 57th St. Suite #422, New York, NY 10019

#endregion

#region Using References

using System;
using System.Threading;
using DynConDevCorp.OpenArch.SupportLibrary.ParallelExecution;

#endregion

namespace DynConDevCorp.OpenArch.Samples.CrossThreadExecutionSample
{
    internal class ThreadInitialization
    {
        #region Public Methods

        public void Execute()
        {
            InitializeThread1();
            InitializeThread2();
            _thread1Started.WaitOne();
            _thread2Started.WaitOne();
            _thread1Started = null;
            _thread2Started = null;
        }

        #endregion

        #region Public Events

        public event EventHandler<EventArgs> Thread1Initialization;
        public event EventHandler<EventArgs> Thread2Initialization;

        #endregion

        #region Private Methods

        private void InitializeThread1()
        {
            _thread1Started = new Semaphore(0, 1);
            _thread1 = new Thread(Thread1Handler) {Name = "Sample Thread #1", IsBackground = true};
            _thread1.Start();
        }

        private void InitializeThread2()
        {
            _thread2Started = new Semaphore(0, 1);
            _thread2 = new Thread(Thread2Handler) {Name = "Sample Thread #2", IsBackground = true};
            _thread2.Start();
        }

        /// <summary>
        /// Will Execute on Thread #1
        /// </summary>
        private void Thread1Handler()
        {
            if (Thread1Initialization != null)
                Thread1Initialization(this, new EventArgs());
            _thread1Started.Release();
            ParallelHostThread.CreateNew(null);
        }


        /// <summary>
        /// Will Execute on Thread #2
        /// </summary>
        private void Thread2Handler()
        {
            if (Thread2Initialization != null)
                Thread2Initialization(this, new EventArgs());
            _thread2Started.Release();
            ParallelHostThread.CreateNew(null);
        }

        #endregion

        #region Instance Fields (Mutable)

        private Thread _thread1;
        private Semaphore _thread1Started;
        private Thread _thread2;
        private Semaphore _thread2Started;

        #endregion
    }
}